package com.xiaojimao.Minio;

import config.MinIOConfigProperties;
import io.minio.*;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Component("minio")
@EnableConfigurationProperties(MinIOConfigProperties.class)
public class MinioService {

    @Autowired
    MinIOConfigProperties minIOConfigProperties;

    public MinioClient getClient() {
        return MinioClient.builder()
                .endpoint(minIOConfigProperties.getMinioEndpoint())
                .credentials(minIOConfigProperties.getMinioAccessKey(), minIOConfigProperties.getMinioSecretKey())
                .build();
    }

    public String uploadFile(MultipartFile file, String minioBucketName) {
        InputStream ip = null;
        try {
            ip = file.getInputStream();

            MinioClient minioClient = getClient();
            // 生成随机的文件名
            String fileName = generateRandomFileName(file.getOriginalFilename());

            // 检查存储桶是否存在，如果不存在则创建
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioBucketName).build());
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioBucketName).build());
            }

            // 将上传的文件保存到本地
            Path tempFilePath = Files.createTempFile("temp-", fileName);
            Files.copy(ip, tempFilePath, StandardCopyOption.REPLACE_EXISTING);
            // 执行文件上传
            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(minioBucketName)
                            .object(fileName)
                            .filename(tempFilePath.toString())
                            .contentType(file.getContentType())
                            .build());

            // 删除临时文件
            Files.delete(tempFilePath);

            // 构建文件访问链接
            String fileUrl = minIOConfigProperties.getMinioEndpoint() + "/" + minioBucketName + "/" + fileName;

            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
            // 处理异常
            return null;
        } finally {
            try {
                ip.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void dow() {
        try {
            // 创建MinIO客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint("http://47.115.220.79:9000")
                    .credentials("minio", "minio123")
                    .build();
            GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                    .bucket("avatar")
                    .object("f9acaadd-96ae-43e8-922b-492d277311af.png")
                    .build();
            // 下载对象
            InputStream inputStream = minioClient.getObject(getObjectArgs);
            OutputStream outputStream = new FileOutputStream("downloaded-image.jpg");

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }

            inputStream.close();
            outputStream.close();

            System.out.println("图片下载成功！");
        } catch (MinioException e) {
            System.out.println("MinIO错误发生: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("发生错误: " + e.getMessage());
        }
    }


    public static void main(String[] args) {
        dow();
    }

    private String generateRandomFileName(String originalFilename) {
        String extension = originalFilename.substring(originalFilename.lastIndexOf('.'));
        return UUID.randomUUID().toString() + extension;
    }

    public byte[] downLoadFile(String pathUrl, String minioBucketName) {
        String key = pathUrl.replace(minIOConfigProperties.getMinioEndpoint() + "/", "");
        int index = key.indexOf("/");
        String bucket = key.substring(0, index);
        String filePath = key.substring(index + 1);
        InputStream inputStream = null;
        try {
            inputStream = getClient().getObject(GetObjectArgs.builder().bucket(minioBucketName).object(filePath).build());
        } catch (Exception e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            try {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }
}
